package cn.edu.cqytxy.dao;

import cn.edu.cqytxy.entity.Weapon;
import cn.edu.cqytxy.util.DBUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 编写武器相关的数据库操作代码
 *
 * @author yinjw
 */
public class WeaponDao {

    /*
     * 查询一般分为两种
     * 1、查询数据列表（筛选）
     * 2、查询单条数据
     *  (做数据库实体和java对象的映射)
     */

    /**
     * 根据id查询武器
     *
     * @param id id
     * @return 武器详情
     */
    public Weapon queryWeaponById(int id) {
        // 获取数据连接
        Connection connection = DBUtils.getConn();

        // 封装sql查询语句
        String sql = "select * from tbl_weapon where id=" + id;

        Weapon weapon = new Weapon();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);

            while (rs.next()) {
                weapon.setId(rs.getInt("id"));
                weapon.setName(rs.getString("name"));
                weapon.setAtt(rs.getInt("att"));
                weapon.setRemake(rs.getString("remake"));
            }
        } catch (Exception e) {
            System.out.println("查询出错");
            e.printStackTrace();
        }
        return weapon;
    }

    public Weapon[] queryWeapon(String name) {
        // 获取数据连接
        Connection connection = DBUtils.getConn();

        // 封装sql查询语句
        String sql = "";
        if (name == null) {
            sql = "select * from tbl_weapon";
        } else {
            sql = "select * from tbl_weapon where name like '%" + name + "%'";
        }
        System.out.println(sql);
        Weapon[] weapons = {};

        try {
            Weapon[] tmpArray = new Weapon[100];
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            int i = 0;
            while (rs.next()) {
                Weapon weapon = new Weapon();
                weapon.setId(rs.getInt("id"));
                weapon.setName(rs.getString("name"));
                weapon.setAtt(rs.getInt("att"));
                weapon.setRemake(rs.getString("remake"));
                tmpArray[i] = weapon;
                i++;
            }
            weapons = new Weapon[i];
            for (int j = 0; j < weapons.length; j++) {
                weapons[j] = tmpArray[j];
            }
        } catch (Exception e) {
            System.out.println("查询出错");
            e.printStackTrace();
        }
        return weapons;
    }

    public static void main(String[] args) {
        WeaponDao weaponDao = new WeaponDao();
        Weapon weapon = weaponDao.queryWeaponById(1);

        Weapon[] weapons = weaponDao.queryWeapon("AK");
        System.out.println(weapons[0].getName());
    }
}
